import { Button } from 'antd';
import React, { useEffect, useState } from 'react';
const CountDown = ({
  children,
  duration = 60,
  onStart,
}: {
  children?: any
  duration?: number,
  onStart: Function
}) => {
  const [loading,setLoading] = useState(false)
  const [seconds, setSeconds] = useState(duration);
  const [isActive, setIsActive] = useState(false);

  const handleStart =async () => {
    if (!isActive) {
      setLoading(true)
      try {
        await onStart();
        setIsActive(true);
      } catch (error) {

      }
      setLoading(false)
    }
  };

  useEffect(() => {
    let interval:any

    if (isActive) {
      interval = setInterval(() => {
        setSeconds(prevSeconds => prevSeconds - 1);
      }, 1000);
    } else {
      clearInterval(interval);
      setSeconds(duration);
    }

    return () => {
      clearInterval(interval);
    };
  }, [isActive, duration]);

  useEffect(() => {
    if (seconds === 0) {
      setIsActive(false);
    }
  }, [seconds]);
  return (<Button loading={loading} type='primary' block onClick={handleStart} disabled={isActive}>
    {isActive ? `等待(${seconds})` : children}
  </Button>)
}
export default CountDown